using ColorFillGame.Application.Commands.Game;
using ColorFillGame.Application.Queries.Game;
using MediatR;
using Microsoft.AspNetCore.Mvc;

namespace ColorFillGame.API.Controllers;

[ApiController]
[Route("api/[controller]")]
public class GameController : ControllerBase
{
    private readonly IMediator _mediator;

    public GameController(IMediator mediator)
    {
        _mediator = mediator;
    }

    [HttpPost]
    public async Task<IActionResult> CreateGame([FromBody] CreateGameRequest request)
    {
        var command = new CreateGameCommand(request.Name, request.GridSize, request.MaxPlayers);
        var gameId = await _mediator.Send(command);
        return CreatedAtAction(nameof(GetGame), new { id = gameId }, gameId);
    }

    [HttpGet("{id}")]
    public async Task<IActionResult> GetGame(Guid id)
    {
        try
        {
            var query = new GetGameQuery(id);
            var game = await _mediator.Send(query);
            return Ok(game);
        }
        catch (ColorFillGame.Domain.Exceptions.GameNotFoundException)
        {
            return NotFound();
        }
    }

    [HttpGet]
    public async Task<IActionResult> GetActiveGames()
    {
        var query = new GetActiveGamesQuery();
        var games = await _mediator.Send(query);
        return Ok(games);
    }

    [HttpPost("{gameId}/join")]
    public async Task<IActionResult> JoinGame(Guid gameId, [FromBody] JoinGameRequest request)
    {
        try
        {
            // 使用空字符串作为ConnectionId，因为API请求没有真实的SignalR连接
            // 实际的连接ID将在客户端建立SignalR连接后通过GameHub更新
            var command = new JoinGameCommand(gameId, request.PlayerName, string.Empty);
            var playerId = await _mediator.Send(command);
            return Ok(playerId);
        }
        catch (ColorFillGame.Domain.Exceptions.GameNotFoundException)
        {
            return NotFound("Game not found");
        }
        catch (ColorFillGame.Domain.Exceptions.GameAlreadyStartedException)
        {
            return BadRequest("Game already started");
        }
        catch (ColorFillGame.Domain.Exceptions.GameRoomFullException)
        {
            return BadRequest("Game room is full");
        }
    }

    [HttpPost("{gameId}/leave")]
    public async Task<IActionResult> LeaveGame(Guid gameId, [FromBody] LeaveGameRequest request)
    {
        try
        {
            var command = new LeaveGameCommand(gameId, request.PlayerId);
            await _mediator.Send(command);
            return NoContent();
        }
        catch (ColorFillGame.Domain.Exceptions.GameNotFoundException)
        {
            return NotFound("Game not found");
        }
        catch (ColorFillGame.Domain.Exceptions.PlayerNotFoundException)
        {
            return NotFound("Player not found");
        }
    }

    [HttpPost("{gameId}/start")]
    public async Task<IActionResult> StartGame(Guid gameId, [FromBody] StartGameRequest request)
    {
        try
        {
            var command = new StartGameCommand(gameId, request.PlayerId);
            await _mediator.Send(command);
            return NoContent();
        }
        catch (ColorFillGame.Domain.Exceptions.GameNotFoundException)
        {
            return NotFound("Game not found");
        }
        catch (ColorFillGame.Domain.Exceptions.GameAlreadyStartedException)
        {
            return BadRequest("Game already started");
        }
        catch (ColorFillGame.Domain.Exceptions.PlayerNotFoundException)
        {
            return NotFound("Player not found");
        }
        catch (ColorFillGame.Domain.Exceptions.DomainException ex)
        {
            return BadRequest(ex.Message);
        }
    }

    [HttpPost("{gameId}/paint")]
    public async Task<IActionResult> PerformPaintAction(Guid gameId, [FromBody] PaintActionRequest request)
    {
        try
        {
            var command = new PaintActionCommand(gameId, request.PlayerId, request.X, request.Y);
            await _mediator.Send(command);
            return NoContent();
        }
        catch (ColorFillGame.Domain.Exceptions.GameNotFoundException)
        {
            return NotFound("Game not found");
        }
        catch (ColorFillGame.Domain.Exceptions.PlayerNotFoundException)
        {
            return NotFound("Player not found");
        }
        catch (ColorFillGame.Domain.Exceptions.InvalidPositionException)
        {
            return BadRequest("Invalid position");
        }
    }

    // 生成临时连接ID（在实际应用中，应该使用身份验证系统）
    private string GenerateConnectionId()
    {
        return Guid.NewGuid().ToString();
    }
}

public class CreateGameRequest
{
    public string Name { get; set; }
    public int GridSize { get; set; }
    public int MaxPlayers { get; set; }
}

public class JoinGameRequest
{
    public string PlayerName { get; set; }
}

public class LeaveGameRequest
{
    public Guid PlayerId { get; set; }
}

public class StartGameRequest
{
    public Guid PlayerId { get; set; }
}

public class PaintActionRequest
{
    public Guid PlayerId { get; set; }
    public int X { get; set; }
    public int Y { get; set; }
}